<template>
  <view class="page-container" :key="pageKey">
    <!-- 1. 顶部搜索栏与门店信息 -->
    <view class="top-bar">
      <view class="search-row">
        <input class="search-input" placeholder="请输入商品名称" />
        <view class="mode-switch">
          <view
            class="mode-btn"
            :class="{ active: orderInfo.mode === 'scan' || orderInfo.mode === 'takeout' }"
            @click="selectMode"
          >{{ orderInfo.mode === 'scan' ? '堂食' : '外卖' }}</view>
          <view class="order-info">
            {{ orderInfo.mode === 'scan' ? `餐桌号: ${orderInfo.board?.boardName}` : '外卖配送' }}
          </view>
        </view>
      </view>
      <view class="store-info">
        <view class="store-left">
          <text>{{ storeInfo.name }}</text>
          <text class="store-arrow">&gt;</text>
        </view>
        <text class="distance">{{ orderInfo.mode === 'takeout' ? `距离您${storeInfo.distance}` : '' }}</text>
      </view>
    </view>

  <view class="main-content">
    <!-- 2. 左侧分类导航栏 -->
    <view class="category-nav">
      <view
        v-for="(item, index) in categories"
        :key="index"
        :class="['category-item', { active: selectedIndex === index }]"
        @click="handleCategoryClick(index)"
      >
        {{ item }}
      </view>
    </view>

    <!-- 3. 右侧商品展示区 -->
    <scroll-view 
      class="product-list" 
      scroll-y 
      :scroll-into-view="currentCategoryId"
      :scroll-with-animation="true"
      @scroll="handleScroll"
      ref="productListRef"
    >
      <view 
        v-for="(category, index) in categories" 
        :key="index"
        :id="`category${index}`"
        class="category-section"
      >
        <view class="category-title">{{ category }}</view>
        <view 
          v-for="dish in getDishesOfCategory(index)" 
          :key="dish.dishId" 
          class="product-item"
        >
          <image :src="`https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${dish.dishImage}`"   class="product-img" />
          <view class="product-info">
            <view class="product-text">
              <text class="product-title">{{ dish.dishName }}</text>
              <text class="product-price">￥{{ dish.price }}</text>
              <text class="sold-quantity">已售 {{ dish.soldQuantity || 0 }}</text>
            </view>
            <button class="spec-btn" @click="openSpecModal(dish)">选规格</button>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>

    <!-- 规格选择浮窗 -->
    <ProductSpecModal :visible="showSpecModal" :dishData="selectedDish" @close="showSpecModal = false" @add-to-cart="handleAddToCart" />
    
    <!-- 点餐模式选择弹窗 -->
    <OrderModeModal :visible="showModeModal" @select="handleModeSelect" />

    <!-- 购物车模块 -->
    <view class="cart-container" v-if="cartItems.length > 0">
      <!-- 预览模式 -->
      <view class="cart-preview" @click="toggleCartDetail">
        <view class="preview-left">
          <view class="cart-icon">
            <image src="/static/member/cart.png" mode="aspectFit" class="cart-image"></image>
            <text class="cart-count">{{ totalQuantity }}</text>
          </view>
          <view class="preview-info">
            <text class="total-price">￥{{ totalPrice }}</text>
          </view>
        </view>
        <view class="preview-right">
          <button class="checkout-btn" @click.stop="handleCheckout">{{ orderInfo.mode === 'scan' ? '提交订单' : '立即结算' }}</button>
        </view>
      </view>

      <!-- 详细模式 -->
      <view class="cart-detail" v-if="showCartDetail">
        <view class="detail-header">
          <text class="detail-title">购物车</text>
          <text class="clear-cart" @click="clearCart">清空购物车</text>
        </view>
        <view class="cart-items">
          <view v-for="(item, index) in cartItems" :key="index" class="cart-item">
            <text class="item-name">{{ item.dishName }}</text>
            <text class="item-price">￥{{ item.price }}</text>
            <view class="item-quantity">
              <text class="quantity-btn" @click.stop="updateCartItemQuantity(index, -1)">-</text>
              <text class="quantity">{{ item.quantity }}</text>
              <text class="quantity-btn" @click.stop="updateCartItemQuantity(index, 1)">+</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import ProductSpecModal from '../../components/ProductSpecModal.vue'
import OrderModeModal from '../../components/OrderModeModal.vue'
import { dishApi, orderApi } from '../../api/index'
import { useOrderStore } from '../../store/order'

// 分类数据
const categories = ref([])
const selectedIndex = ref(0)  // 当前选中的分类索引
const productListRef = ref(null)  // 商品列表容器的引用
const dishes = ref([])  // 存储菜品数据
const currentCategoryId = ref('')

// 订单信息
let orderInfo = ref({
  mode: '',  // 点餐模式：scan 或 takeout
  board: '' // 餐桌号
})



// 添加页面key用于强制更新
const pageKey = ref(0)

// 获取分类数据
async function fetchCategories() {
  try {
    const res = await dishApi.getDishTypes()
    // 检查是否已经包含热门分类
    if (!res.data.includes('热门')) {
      categories.value = ['热门', ...res.data]
    } else {
      categories.value = res.data
    }
    console.log('分类列表:', res)
  } catch (error) {
    console.error('获取分类列表失败:', error)
    uni.showToast({
      title: '获取分类列表失败',
      icon: 'none'
    })
  }
}

// 获取菜品数据
async function selectCategory() {
  try {
    const res = await dishApi.getDishList()
    // 更新菜品列表
    dishes.value = res.data
    console.log('菜品列表:', res)
    
    // 输出第一个菜品数据结构，查看字段名
    if (res.data && res.data.length > 0) {
      console.log('菜品数据结构示例:', JSON.stringify(res.data[0]))
    }
  } catch (error) {
    console.error('获取菜品列表失败:', error)
    uni.showToast({
      title: '获取菜品列表失败',
      icon: 'none'
    })
  }
}

// 点餐模式相关
const showModeModal = ref(true)  // 默认显示模式选择弹窗

// 控制规格选择浮窗的显示隐藏
const showSpecModal = ref(false)

// 存储当前选中的菜品数据（默认数据）
const selectedDish = ref({
  dish_image: '/static/placeholder-image.jpg',  // 默认图片路径
  dish_name: '默认菜品名称',
  price: 9.99,
  dish_describe: '这是一个默认菜品的描述信息。\
这个描述可以稍微长一点，以便测试文字显示效果。\
例如，这里可以包含菜品的特点、配料、口味介绍等详细信息。'
})

// 点击"选规格"按钮时触发，更新 selectedDish 并显示浮窗
function openSpecModal(dish) {
  selectedDish.value = dish
  // 显示规格选择浮窗
  showSpecModal.value = true
}

// 店铺信息
const storeInfo = ref({
  name: '俊兴海鲜大排档(横琴长隆宝兴路店)',
  latitude: 22.1144,  // 店铺纬度
  longitude: 113.5450,  // 店铺经度
  distance: '--'
})

// 获取用户位置并计算距离
const getLocationAndDistance = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      const { latitude, longitude } = res
      // 使用高德地图路径规划API计算实际道路距离
      const key = '051584ac691a71f56f602155d0c6b315'  // 高德地图API密钥
      const url = `https://restapi.amap.com/v3/distance?origins=${longitude},${latitude}&destination=${storeInfo.value.longitude},${storeInfo.value.latitude}&type=1&key=${key}`
      
      uni.request({
        url: url,
        success: (res) => {
          if (res.data.status === '1' && res.data.results && res.data.results.length > 0) {
            const distance = res.data.results[0].distance
            if (distance < 1000) {
              storeInfo.value.distance = `${Math.round(distance)}m`
            } else {
              storeInfo.value.distance = `${(distance/1000).toFixed(1)}km`
            }
          } else {
            console.error('计算距离失败：', res.data)
            if (res.data.infocode === '10001') {
              uni.showToast({
                title: '地图服务配置错误',
                icon: 'none'
              })
            } else {
              uni.showToast({
                title: res.data.info || '计算距离失败',
                icon: 'none'
              })
            }
            storeInfo.value.distance = '--'
          }
        },
        fail: (err) => {
          console.error('请求失败：', err)
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
          storeInfo.value.distance = '--'
        }
      })
    },
    fail: (err) => {
      console.error('获取位置失败：', err)
      uni.showToast({
        title: '获取位置失败',
        icon: 'none'
      })
      storeInfo.value.distance = '--'
    }
  })
}

// 获取指定分类的菜品
function getDishesOfCategory(index) {
  const category = categories.value[index]
  if (category === '热门') {
    // 返回非冷菜类型中销量最高的5个菜品，且只返回出售状态为0的菜品
    return dishes.value
      .filter(dish => {
        // 检查菜品是否属于非冷菜类型
        const isNotColdDish = dish.dtId !== 1;
        
        // 检查菜品状态是否为0（出售状态）
        // 考虑不同的可能字段名
        const dishStatus = dish.dishStatus !== undefined ? dish.dishStatus : 
                          (dish.dish_status !== undefined ? dish.dish_status : null);
        
        return isNotColdDish && dishStatus === 0;
      })
      .sort((a, b) => (b.soldQuantity || 0) - (a.soldQuantity || 0))
      .slice(0, 5)
  } else {
    // 返回指定分类的菜品，并按照priority升序，再按dish_id升序排列，且只返回出售状态的菜品
    return dishes.value
      .filter(dish => {
        // 检查菜品是否属于当前分类
        const belongsToCategory = dish.dtId === index;
        
        // 检查菜品状态是否为0（出售状态）
        // 考虑不同的可能字段名
        const dishStatus = dish.dishStatus !== undefined ? dish.dishStatus : 
                          (dish.dish_status !== undefined ? dish.dish_status : null);
        
        return belongsToCategory && dishStatus === 0;
      })
      .sort((a, b) => {
        // 首先按priority升序排列
        if ((a.priority || 0) !== (b.priority || 0)) {
          return (a.priority || 0) - (b.priority || 0)
        }
        // 如果priority相同，则按dish_id升序排列
        return (a.dishId || 0) - (b.dishId || 0)
      })
  }
}

// 处理分类点击事件
function handleCategoryClick(index) {
  selectedIndex.value = index
  // const categoryId = categories.value[index].dtId
  currentCategoryId.value = `category${index}`
}

// 处理滚动事件
function handleScroll(e) {
  // 获取当前滚动位置
  const scrollTop = e.detail.scrollTop

  // 获取所有分类区域的位置信息
  const query = uni.createSelectorQuery()
  query.selectAll('.category-section').boundingClientRect(rects => {
    if (!rects) return
    
    // 找到当前在视图中的分类
    const visibleSection = rects.find(rect => {
      const offsetTop = rect.top
      return offsetTop >= 0 && offsetTop <= 300 // 可视区域的阈值
    })

    if (visibleSection) {
      // 从元素的id中提取索引
      const index = parseInt(visibleSection.id.replace('category', ''))
      if (!isNaN(index) && index !== selectedIndex.value) {
        selectedIndex.value = index
      }
    }
  })
  query.exec()
}

// 处理模式选择
const handleModeSelect = async (data) => {
  let order = ref([])
  //判断是否是扫码点餐
  if (data.mode === 'scan') {
    //判断扫码是否成功 - 餐桌状态是否是空闲，不是空闲则提示
    if (data.board.code != 200) {
      uni.showToast({
        title:data.board.msg,
        icon: 'none'
      })
      return
    }
    //如果是空闲，则赋值
    order.value = {
      mode: data.mode,
      board: data.board.data
    }
  } else {
    order.value = data
  }
  orderInfo.value = order.value
  showModeModal.value = false
  
  // 强制更新页面
  pageKey.value++
  
  // 等待DOM更新
  await nextTick()
  
  // 如果选择外卖模式，自动获取用户位置
  if (data.mode === 'takeout') {
    getLocationAndDistance()
  }
  
  // 重新获取数据
  await selectCategory()
  await fetchCategories()
}

// 初始化数据的函数
const initializeData = async () => {
  // 重新获取数据
  await selectCategory()
  await fetchCategories()
  
  // 如果选择外卖模式，自动获取用户位置
  if (orderInfo.value.mode === 'takeout') {
    getLocationAndDistance()
  }
}

// 获取页面参数
const orderId = ref(null)

function selectMode() {
  if(orderId.value != null) {
    showModeModal.value = false
  } else {
    showModeModal.value = true
  }
}

// 每次页面显示时重新获取数据
onShow(async () => {
  // 页面加载时的初始化逻辑
  const pendingOrderId = uni.getStorageSync('orderId')
  console.log('pendingOrderId:', pendingOrderId)
  if (pendingOrderId) {
    orderId.value = pendingOrderId
    console.log("orderId:", orderId.value);
    checkOrderStatus()
    // 清空购物车
    cartItems.value = []
    totalPrice.value = 0
    showCartDetail.value = false
  }
  // 检查是否有新的订单信息
  const info = uni.getStorageSync('orderInfo')
  if (info) {
    orderInfo.value = JSON.parse(info)
    console.log('订单信息：', orderInfo.value)
    uni.removeStorageSync('orderInfo')
    showModeModal.value = false
    
    // 强制更新页面
    pageKey.value++
    
    // 等待DOM更新
    await nextTick()
  }
  
  // 初始化数据
  await initializeData()
})

// 检查订单状态
const checkOrderStatus = async () => {
  try {
    // TODO: 实际项目中替换为真实的API调用
    const res = await orderApi.getOrderDetail(orderId.value)
    const orderData = res.data
    console.log("res:", res)
    console.log('订单详情:', orderData)
    
    // 如果订单状态为待支付(1)，则不显示选择点餐方式的弹窗
    if (orderData.订单状态 === "待支付") {
      showModeModal.value = false
      // 直接设置堂食模式
      orderInfo.value = {
        mode: 'scan',
        board: {
          boardId: 125,
          boardName: orderData.餐桌名称
        }
      }
    } else {
      console.log("错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误错误")
      // 如果订单状态不是待支付，清除本地存储中的订单编号
      uni.removeStorageSync('orderId')
    }
  } catch (error) {
    console.log("失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败失败")
    uni.removeStorageSync('orderId')
    console.error('获取订单详情失败:', error)
    uni.showToast({
      title: '获取订单详情失败',
      icon: 'none'
    })
  }
}

// 购物车相关状态
const cartItems = ref([])
const totalPrice = ref(0)
const showCartDetail = ref(false)

// 计算总数量
const totalQuantity = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

// 切换购物车详情显示
const toggleCartDetail = () => {
  showCartDetail.value = !showCartDetail.value
}

// 清空购物车
const clearCart = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空购物车吗？',
    success: (res) => {
      if (res.confirm) {
        cartItems.value = []
        totalPrice.value = 0
        showCartDetail.value = false
      }
    }
  })
}

// 处理添加到购物车
const handleAddToCart = (item) => {
  const existingItem = cartItems.value.find(cartItem => cartItem.dishId === item.dishId)
  if (existingItem) {
    existingItem.quantity += item.quantity
  } else {
    cartItems.value.push({
      ...item,
      quantity: item.quantity
    })
  }
  calculateTotalPrice()
  showSpecModal.value = false
}

// 更新购物车商品数量
const updateCartItemQuantity = (index, change) => {
  const item = cartItems.value[index]
  const newQuantity = item.quantity + change
  if (newQuantity > 0) {
    item.quantity = newQuantity
  } else {
    cartItems.value.splice(index, 1)
  }
  calculateTotalPrice()
}

// 计算总价
const calculateTotalPrice = () => {
  totalPrice.value = cartItems.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)
}

// 处理结算
const handleCheckout = () => {
  const orderStore = useOrderStore()
  const info = {
    storeInfo: storeInfo.value,
    orderInfo: orderInfo.value,
    cartItems: cartItems.value
  }
  // 存储订单数据到 Pinia store
  orderStore.setOrderData(info)
  // 跳转到支付页面
  uni.navigateTo({
    url: 'payment'
  })
}
</script>

<style lang="scss" scoped>
.page-container {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.top-bar {
  padding: 6px 16px 16px 16px;
  background: #f8f8f8;
  flex-shrink: 0;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.search-input {
  flex: 1 1 0;
  max-width: 320px;
  min-width: 100px;
  padding: 8px;
  border-radius: 8px;
  border: 1px solid #eee;
  background: #fff;
}

.mode-switch {
  display: flex;
  align-items: center;
  background: #e0e0e0;
  border-radius: 16px;
  overflow: hidden;
  height: 28px;
  padding-right: 12px;
}

.mode-btn {
  padding: 0 12px;
  height: 28px;
  line-height: 28px;
  font-size: 12px;
  color: #444;
  background: transparent;
  transition: all 0.2s;
  
  &.active {
    background: #2196f3;
    color: #fff;
  }
}

.order-info {
  margin-left: 8px;
  font-size: 12px;
  color: #666;
}

.store-info {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 36px;
  padding: 6px 0;
  justify-content: space-between;
}

.store-left {
  display: flex;
  align-items: center;
  gap: 4px;
}

.store-arrow {
  font-size: 16px;
  color: #888;
  margin-left: 2px;
}

.distance {
  color: #888;
  font-size: 12px;
}

.main-content {
  display: flex;
  flex: 1;
  width: 100%;
  overflow: hidden;
  position: relative;
  height: calc(100vh - 100px); // 减去顶部搜索栏的高度
}

.category-nav {
  width: 80px;
  background: #f5f5f5;
  flex-shrink: 0;
  height: 100%;
  overflow-y: auto;
  position: sticky;
  top: 0;
  left: 0;
  -webkit-overflow-scrolling: touch;
}

.category-item {
  padding: 10px 8px;
  cursor: pointer;
  font-size: 12px;
  transition: color 0.2s, background 0.2s;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
}

.category-item.active {
  background: #2196f3;
  color: #fff;
}

.product-list {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
  height: 100%;
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
}

.category-section {
  margin-bottom: 20px;
}

.category-title {
  font-size: 16px;
  font-weight: bold;
  padding: 10px 0;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 1;
}

.product-item {
  display: flex;
  margin-bottom: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
  padding: 12px;
  align-items: center;
}

.product-img {
  width: 80px;
  height: 80px;
  margin-right: 12px;
  border-radius: 8px;
  background: #f0f0f0;
  flex-shrink: 0;
  object-fit: cover;
}

.product-info {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.product-text {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  flex-grow: 1;
  flex-shrink: 1;
  min-width: 0;
  margin-right: 8px;
  justify-content: center;
}

.product-title {
  font-weight: bold;
  margin-bottom: 0px;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.3;
}

.product-price {
  display: block;
  color: #888;
  margin-top: 5px;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: normal;
  line-height: 1.3;
}

.sold-quantity {
  display: block;
  color: #999;
  font-size: 12px;
  margin-top: 2px;
  line-height: 1.3;
}

.spec-btn {
  flex-shrink: 0;
  background: #008CB5;
  color: #fff;
  border: none;
  border-radius: 14px;
  padding: 0 12px;
  font-size: 12px;
  height: 28px;
  min-width: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: auto;
  margin-top: 30px;
}

.cart-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
  display: flex;
  flex-direction: column;
}

.cart-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
  flex-shrink: 0;
}

.preview-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.cart-icon {
  position: relative;
  width: 40px;
  height: 40px;
  background: #008CB5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-image {
  width: 24px;
  height: 24px;
}

.cart-count {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #ff6b6b;
  color: #fff;
  font-size: 12px;
  min-width: 18px;
  height: 18px;
  border-radius: 9px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
}

.preview-info {
  display: flex;
  flex-direction: column;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b6b;
}

.preview-right {
  display: flex;
  align-items: center;
}

.cart-detail {
  background: #fff;
  border-top: 1px solid #eee;
  max-height: 30vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
}

.detail-title {
  font-size: 16px;
  font-weight: bold;
}

.clear-cart {
  color: #999;
  font-size: 14px;
}

.cart-items {
  padding: 0 16px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  flex: 1;
}

.cart-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.item-name {
  flex: 1;
  font-size: 14px;
}

.item-price {
  color: #ff6b6b;
  margin: 0 16px;
}

.item-quantity {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 24px;
  height: 24px;
  border: 1px solid #ddd;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #666;
}

.quantity {
  margin: 0 8px;
  min-width: 20px;
  text-align: center;
}

.checkout-btn {
  background: #008CB5;
  color: #fff;
  border: none;
  border-radius: 20px;
  padding: 8px 24px;
  font-size: 14px;
}
</style>